import logging
import time

from django.utils.deprecation import MiddlewareMixin


class LogMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.init_time = time.time()
        return None

    def process_response(self, request, response):
        try:
            # 请求响应总时长
            total_time = time.time() - request.init_time
            # 请求方式
            method = request.method
            # 请求路径
            path = request.path
            # 访问状态码
            status_code = response.status_code
            # 访问内容
            content = response.content
            message = '%s %s %s %s %s' % (total_time, method, path, status_code, content)
            logging.info(message)
        except:
            logging.critical('系统错误')

        return response

